<template>
    <zt-dialog v-model="visible" title="角色分配" @confirm="confirmBtn" :loading="isLoading" :showFooter="true"
        :showFullScreen="false" width="800px" height="600px" :showConfirm="true">
        <el-transfer :titles="['可选角色', '已有角色']" :props="configData" v-model="selectValue" :data="roleList" />
    </zt-dialog>
</template>

<script setup>
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { apiGetRoleList, apiGetUserRole } from '@/api/common/api.js'
import { apiPutRoleAssign } from "@/api/admin/systemSettings/accountManage/api.js"
const isLoading = ref(false)
const emit = defineEmits(['success', 'update:modelValue'])
const props = defineProps({
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})
// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        emit('update:modelValue', value)
    },
})
const configData = reactive({
    key: 'roleId',
    label: 'roleName',
})

// 确认按钮
async function confirmBtn() {
    isLoading.value = true
    apiPutRoleAssign({
        userId: props.objectValue.userId,
        roleIds: selectValue.value,
    }).then(res => {
        isLoading.value = false
        if (res.success) {
            ElMessage({
                message: '分配成功',
                type: 'success',
            })
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    })

}

const selectValue = ref([]) //已选角色
const roleList = ref([])
// 获取角色列表数据
async function getRoleList() {
    apiGetRoleList({
        page: 1,
        limit: -1,
    }).then(res => {
        roleList.value = res.data.records
    })
}

// 获取已有的用户角色数据
async function getRoleAssignment() {
    apiGetUserRole({
        userId: props.objectValue.userId
    }).then(res => {
        selectValue.value = res.data.map(item => item.roleId)||[]
    })
}

getRoleList()
getRoleAssignment()
</script>

<style lang='scss' scoped></style>
<style>
.el-transfer {
    --el-transfer-panel-width: 300px;
    --el-transfer-panel-body-height: 420px;
}
</style>